<template>
  <div class="sync-strategy-edit">
    <el-card>
      <div slot="header" class="clearfix">
        <span>编辑同步策略</span>
      </div>
      
      <el-form ref="strategyForm" :model="strategy" :rules="rules" label-width="120px">
        <el-form-item label="策略名称" prop="strategyName">
          <el-input v-model="strategy.strategyName" placeholder="请输入策略名称"></el-input>
        </el-form-item>
        
        <el-form-item label="源数据库" prop="sourceDbConfigId">
          <el-select v-model="strategy.sourceDbConfigId" placeholder="请选择源数据库">
            <el-option
              v-for="db in databaseConfigs"
              :key="db.id"
              :label="db.configName"
              :value="db.id"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="目标数据库" prop="targetDbConfigId">
          <el-select v-model="strategy.targetDbConfigId" placeholder="请选择目标数据库">
            <el-option
              v-for="db in databaseConfigs"
              :key="db.id"
              :label="db.configName"
              :value="db.id"
            ></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="同步类型" prop="syncType">
          <el-radio-group v-model="strategy.syncType">
            <el-radio label="FULL">全量同步</el-radio>
            <el-radio label="INCREMENTAL">增量同步</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="同步间隔" prop="syncInterval">
          <el-input-number v-model="strategy.syncInterval" :min="0" :max="86400" placeholder="0表示手动触发"></el-input-number>
          <span style="margin-left: 10px;">秒</span>
        </el-form-item>
        
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="strategy.status">
            <el-radio label="ENABLED">启用</el-radio>
            <el-radio label="DISABLED">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="数据获取规则" prop="dataFetchRule">
          <el-input
            v-model="strategy.dataFetchRule"
            type="textarea"
            :rows="6"
            placeholder="请输入JSON格式的数据获取规则"
          ></el-input>
        </el-form-item>
        
        <el-form-item label="策略描述" prop="description">
          <el-input
            v-model="strategy.description"
            type="textarea"
            :rows="3"
            placeholder="请输入策略描述（选填）"
          ></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleSubmit">提交</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
export default {
  name: 'SyncStrategyEdit',
  data() {
    return {
      strategy: {
        id: null,
        strategyName: '',
        sourceDbConfigId: null,
        targetDbConfigId: null,
        dataFetchRule: '',
        syncType: 'FULL',
        syncInterval: 0,
        status: 'ENABLED',
        description: ''
      },
      databaseConfigs: [],
      rules: {
        strategyName: [
          { required: true, message: '请输入策略名称', trigger: 'blur' },
          { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              this.checkStrategyNameUnique(value, callback);
            },
            trigger: 'blur'
          }
        ],
        sourceDbConfigId: [
          { required: true, message: '请选择源数据库', trigger: 'change' }
        ],
        targetDbConfigId: [
          { required: true, message: '请选择目标数据库', trigger: 'change' }
        ],
        dataFetchRule: [
          { required: true, message: '请输入数据获取规则', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              try {
                JSON.parse(value);
                callback();
              } catch (error) {
                callback(new Error('数据获取规则必须是有效的JSON格式'));
              }
            },
            trigger: 'blur'
          }
        ],
        syncType: [
          { required: true, message: '请选择同步类型', trigger: 'change' }
        ],
        status: [
          { required: true, message: '请选择状态', trigger: 'change' }
        ],
        syncInterval: [
          { required: true, message: '请输入同步间隔', trigger: 'blur' },
          { type: 'number', min: 0, message: '同步间隔不能小于0', trigger: 'blur' }
        ]
      }
    };
  },
  mounted() {
    // 获取策略ID
    const id = this.$route.query.id;
    if (id) {
      this.loadStrategy(id);
    } else {
      this.$message.error('参数错误，未指定策略ID');
      this.$router.push('/sync-strategy');
    }
    // 加载数据库配置
    this.loadDatabaseConfigs();
  },
  methods: {
    loadStrategy(id) {
      this.$api.syncStrategyApi.getById(id)
        .then(res => {
          this.strategy = res && res.data || {};
        })
        .catch(error => {
          this.$message.error('获取策略信息失败: ' + error.message);
          this.$router.push('/sync-strategy');
        });
    },
    
    loadDatabaseConfigs() {
      this.$api.databaseConfigApi.getAll()
        .then(res => {
          this.databaseConfigs = res && res.data || [];
        })
        .catch(error => {
          this.$message.error('获取数据库配置列表失败: ' + error.message);
        });
    },
    
    checkStrategyNameUnique(name, callback) {
      // 如果名称没有修改，则直接通过验证
      if (name === this.strategy.strategyName) {
        callback();
        return;
      }
      
      this.$api.syncStrategyApi.checkName(name)
        .then(res => {
          if (res && res.data && res.data.id !== this.strategy.id) {
            callback(new Error('策略名称已存在'));
          } else {
            callback();
          }
        })
        .catch(error => {
          // 如果请求失败（例如404），表示名称可用
          callback();
        });
    },
    
    handleSubmit() {
      this.$refs.strategyForm.validate((valid) => {
        if (valid) {
          // 验证JSON格式
          try {
            JSON.parse(this.strategy.dataFetchRule);
          } catch (error) {
            this.$message.error('数据获取规则必须是有效的JSON格式');
            return;
          }
          
          // 提交表单
          this.$api.syncStrategyApi.update(this.strategy.id, this.strategy)
            .then(() => {
              this.$message.success('更新成功');
              this.$router.push('/sync-strategy');
            })
            .catch(error => {
              this.$message.error('更新失败: ' + error.message);
            });
        } else {
          return false;
        }
      });
    },
    
    handleCancel() {
      this.$router.push('/sync-strategy');
    }
  }
};
</script>

<style scoped>
.sync-strategy-edit {
  padding: 20px;
}
</style>